import React, { useState, useMemo } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Modal } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { usePlans } from '../hooks/usePlans';
import { getToday, getTomorrow, getYesterday } from '../utils/dateUtils';
import { createCommonStyles } from '../styles/commonStyles';
import { useTheme } from '../hooks/useTheme';
import Button from '../components/common/Button';
import Input from '../components/common/Input';
import PlanItem from '../components/plan/PlanItem';
import usePlanStore from '../store/planStore';

const DailyScreen = () => {
  const { addPlan, getPlansByDate } = usePlans();
  const { plans, togglePlanStatus, updatePlan, deletePlan } = usePlanStore();
  const { theme } = useTheme();
  const dynamicStyles = createCommonStyles(theme);
  const today = getToday();
  const tomorrow = getTomorrow();
  const yesterday = getYesterday();
  const [selectedDate, setSelectedDate] = useState('today'); // 'yesterday', 'today' 或 'tomorrow'
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingPlan, setEditingPlan] = useState(null);
  const [newPlanTitle, setNewPlanTitle] = useState('');
  const [newPlanDescription, setNewPlanDescription] = useState('');

  // 根据选择的日期获取计划
  const currentDate = selectedDate === 'today' ? today : selectedDate === 'tomorrow' ? tomorrow : yesterday;
  const isViewingPast = selectedDate === 'yesterday'; // 是否查看昨日（只读模式）
  const currentPlans = useMemo(() => {
    return getPlansByDate(currentDate);
  }, [plans, getPlansByDate, currentDate]);

  const handleAddPlan = () => {
    if (newPlanTitle.trim()) {
      addPlan({
        title: newPlanTitle,
        description: newPlanDescription,
        scheduledFor: currentDate,
      });
      setNewPlanTitle('');
      setNewPlanDescription('');
      setShowAddModal(false);
    }
  };

  const handleEditPlan = (plan) => {
    setEditingPlan(plan);
    setNewPlanTitle(plan.title);
    setNewPlanDescription(plan.description || '');
    setShowEditModal(true);
  };

  const handleUpdatePlan = () => {
    if (newPlanTitle.trim() && editingPlan) {
      updatePlan(editingPlan.id, {
        title: newPlanTitle,
        description: newPlanDescription,
      });
      setNewPlanTitle('');
      setNewPlanDescription('');
      setEditingPlan(null);
      setShowEditModal(false);
    }
  };

  const handleDeletePlan = (planId) => {
    deletePlan(planId);
  };

  const closeModals = () => {
    setShowAddModal(false);
    setShowEditModal(false);
    setEditingPlan(null);
    setNewPlanTitle('');
    setNewPlanDescription('');
  };

  return (
    <SafeAreaView style={[dynamicStyles.container, { backgroundColor: theme.colors.background }]} edges={['top']}>
      <ScrollView style={[dynamicStyles.content, { backgroundColor: theme.colors.background }]}>
        {/* 日期切换标签 */}
        <View style={styles.tabContainer}>
          <TouchableOpacity
            style={[
              styles.tab,
              selectedDate === 'yesterday' && [styles.tabActive, { backgroundColor: theme.colors.primary }],
              selectedDate !== 'yesterday' && { backgroundColor: theme.colors.surface }
            ]}
            onPress={() => setSelectedDate('yesterday')}
          >
            <Text style={[
              styles.tabText,
              { color: selectedDate === 'yesterday' ? '#FFFFFF' : theme.colors.text }
            ]}>
              昨日
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              styles.tab,
              selectedDate === 'today' && [styles.tabActive, { backgroundColor: theme.colors.primary }],
              selectedDate !== 'today' && { backgroundColor: theme.colors.surface }
            ]}
            onPress={() => setSelectedDate('today')}
          >
            <Text style={[
              styles.tabText,
              { color: selectedDate === 'today' ? '#FFFFFF' : theme.colors.text }
            ]}>
              今日
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[
              styles.tab,
              selectedDate === 'tomorrow' && [styles.tabActive, { backgroundColor: theme.colors.primary }],
              selectedDate !== 'tomorrow' && { backgroundColor: theme.colors.surface }
            ]}
            onPress={() => setSelectedDate('tomorrow')}
          >
            <Text style={[
              styles.tabText,
              { color: selectedDate === 'tomorrow' ? '#FFFFFF' : theme.colors.text }
            ]}>
              明日
            </Text>
          </TouchableOpacity>
        </View>

        <View style={styles.header}>
          <Text style={[styles.subtitle, { color: theme.colors.textSecondary }]}>
            {selectedDate === 'today' ? '今日计划' : selectedDate === 'tomorrow' ? '明日计划' : '昨日计划'}
          </Text>
        </View>

        {currentPlans.length === 0 ? (
          <View style={styles.emptyContainer}>
            <Text style={[styles.emptyText, { color: theme.colors.textSecondary }]}>
              {selectedDate === 'today' ? '今天还没有计划' : selectedDate === 'tomorrow' ? '明天还没有计划' : '昨天还没有计划'}
            </Text>
            {!isViewingPast && (
              <Text style={[styles.emptyHint, { color: theme.colors.textSecondary }]}>点击下方按钮添加计划</Text>
            )}
          </View>
        ) : (
          <View>
            {currentPlans.map((plan) => {
              // 昨日计划不允许编辑和删除
              const canDelete = !isViewingPast;
              const canEdit = !isViewingPast;
              
              return (
                <PlanItem
                  key={plan.id}
                  plan={plan}
                  onToggle={() => togglePlanStatus(plan.id)}
                  onEdit={() => handleEditPlan(plan)}
                  onDelete={() => handleDeletePlan(plan.id)}
                  canDelete={canDelete}
                  canEdit={canEdit}
                />
              );
            })}
          </View>
        )}
      </ScrollView>

      {/* 添加计划按钮 - 昨日模式下隐藏 */}
      {!isViewingPast && (
        <View style={styles.fabContainer}>
          <TouchableOpacity
            style={[styles.fab, { backgroundColor: theme.colors.primary }]}
            onPress={() => setShowAddModal(true)}
            activeOpacity={0.7}
          >
            <Text style={styles.fabText}>+</Text>
          </TouchableOpacity>
        </View>
      )}

      {/* 添加/编辑计划模态框 */}
      <Modal
        visible={showAddModal || showEditModal}
        transparent={true}
        animationType="slide"
        onRequestClose={closeModals}
      >
        <View style={[styles.modalOverlay, { backgroundColor: 'rgba(0, 0, 0, 0.5)' }]}>
          <View style={[styles.modalContent, { backgroundColor: theme.colors.card }]}>
            <Text style={[styles.modalTitle, { color: theme.colors.text }]}>
              {showEditModal ? '编辑计划' : '添加新计划'}
            </Text>
            
            <Input
              label="计划标题"
              value={newPlanTitle}
              onChangeText={setNewPlanTitle}
              placeholder="请输入计划标题"
            />
            
            <Input
              label="详细描述（可选）"
              value={newPlanDescription}
              onChangeText={setNewPlanDescription}
              placeholder="请输入详细描述"
              multiline
            />

            <View style={styles.modalButtons}>
              <Button
                title="取消"
                variant="secondary"
                onPress={closeModals}
                style={styles.modalButton}
              />
              <Button
                title={showEditModal ? '保存' : '添加'}
                onPress={showEditModal ? handleUpdatePlan : handleAddPlan}
                style={styles.modalButton}
              />
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  tabContainer: {
    flexDirection: 'row',
    marginBottom: 16,
    gap: 8,
  },
  tab: {
    flex: 1,
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderRadius: 8,
    alignItems: 'center',
    justifyContent: 'center',
  },
  tabActive: {
    // 背景色在样式中动态设置
  },
  tabText: {
    fontSize: 16,
    fontWeight: '600',
  },
  header: {
    marginBottom: 24,
  },
  dateText: {
    fontSize: 32,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 18,
    marginBottom: 8,
  },
  emptyHint: {
    fontSize: 14,
  },
  planTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 4,
  },
  planDescription: {
    fontSize: 14,
  },
  fabContainer: {
    position: 'absolute',
    bottom: 20,
    right: 20,
    zIndex: 1000,
  },
  fab: {
    width: 48,
    height: 48,
    borderRadius: 24,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  fabText: {
    fontSize: 28,
    color: '#FFFFFF',
    fontWeight: '300',
    lineHeight: 28,
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'flex-end',
  },
  modalContent: {
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 24,
    paddingBottom: 40,
    maxHeight: '80%',
  },
  modalTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 24,
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 24,
    gap: 12,
  },
  modalButton: {
    flex: 1,
  },
});

export default DailyScreen;

